'use client';

import type { IPagination, IQueryParams, ITagGroup } from '@/interfaces';
import { queryAllTagGroup, searchTagGroup } from '@/services/api';
import { type ChangeEvent, useContext, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import classNames from 'classnames';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import { TagGroupAdminContext } from '@/contexts/admin/forum/tagGroup';
import { useSearchParams } from 'next/navigation';
import useToast from '@/hooks/useToast';
import CreateTagGroupAdminPage from '@/app/[locale]/admin/forum/tagGroup/create';
import DetailsTagGroupAdminPage from '@/app/[locale]/admin/forum/tagGroup/detail';
import UpdateTagGroupAdminPage from '@/app/[locale]/admin/forum/tagGroup/update';

export default function ListTagGroupAdminPage(this: any) {
  const { show } = useToast();
  const urlSearchParams = useSearchParams();
  const [params, setParams] = useState<IQueryParams>({
    page: urlSearchParams?.has('page')
      ? parseInt(urlSearchParams.get('page') + '')
      : 0,
  });
  const [searchName, setSearchName] = useState('');
  const queryKey = ['/forum', '/tagGroups', params, searchName];
  const [isCreate, setIsCreate] = useState(false);
  const [detailItem, setDetailItem] = useState<ITagGroup>();
  const [updateItem, setUpdateItem] = useState<ITagGroup>();
  const context = useContext(TagGroupAdminContext);
  const [currentItemId, setCurrentItemId] = useState<number>();

  const queryAllTagQuery = useQuery(
    queryKey,
    async (context) => {
      if (searchName) {
        return (await searchTagGroup({
          query: {
            ...(context.queryKey[2] as any),
            name: context.queryKey[3],
          },
        })) as IPagination<ITagGroup>;
      } else {
        return (await queryAllTagGroup({
          query: context.queryKey[2] as any,
        })) as IPagination<ITagGroup>;
      }
    },
    {
      keepPreviousData: true,
    },
  );

  function onChangeSearch(e: ChangeEvent<HTMLInputElement>) {
    const value = e.target.value.trim();
    setSearchName(value.toLowerCase());
  }

  function onClickCreate() {
    setIsCreate(true);
  }

  function onClickDetail(item: ITagGroup) {
    setDetailItem(item);
    setCurrentItemId(item.id);
  }

  function onClickUpdate(item: ITagGroup) {
    setUpdateItem(item);
  }

  function onClickPrevious() {
    const data = queryAllTagQuery.data;
    if (!data) {
      show({
        type: 'DANGER',
        message: '数据不存在',
      });
      return;
    }

    const page = Math.max(0, data.pageable.page - 1);
    setParams({ ...params, page });
  }

  function onClickNext() {
    const data = queryAllTagQuery.data;
    if (!data) {
      show({
        type: 'DANGER',
        message: '数据不存在',
      });
      return;
    }

    const page = Math.min(data.pageable.pages, data.pageable.page + 1);
    setParams({ ...params, page });
  }

  if (queryAllTagQuery.data) {
    const data = queryAllTagQuery.data;

    return (
      <TagGroupAdminContext.Provider
        value={{
          ...context,
          isCreate,
          detailItem,
          updateItem,
          setIsCreate,
          setDetailItem,
          setUpdateItem,
          queryKey,
        }}
      >
        <div className="row">
          <div className="col">
            <div className="vstack gap-4">
              {isCreate ? (
                <CreateTagGroupAdminPage />
              ) : (
                <div className="row">
                  <div className="col">
                    <div className="card">
                      <div className="card-header bg-transparent">
                        <div className="row row-cols-auto justify-content-between g-2">
                          <div className="col">
                            <div className="input-group">
                              <span className="input-group-text">
                                <i className="bi bi-search"></i>
                              </span>
                              <input
                                onChange={onChangeSearch}
                                type="search"
                                className="form-control"
                                placeholder="搜索标签组"
                              />
                            </div>
                          </div>
                          <div className="col">
                            <div className="hstack gap-3">
                              <button
                                onClick={onClickCreate}
                                type="button"
                                className="btn btn-primary"
                              >
                                <i className="bi bi-plus-lg me-2"></i>
                                新增标签组
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div className="card-body">
                        <div className="table-responsive">
                          <table className="table table-hover align-middle">
                            <thead>
                              <tr className="text-nowrap">
                                <th scope="col" className="w-10">
                                  ID
                                </th>
                                <th scope="col" className="w-10">
                                  名称
                                </th>
                                <th scope="col" className="w-10"></th>
                              </tr>
                            </thead>
                            <tbody>
                              {data.content.map((item) => {
                                return (
                                  <tr
                                    key={item.id}
                                    className={classNames('text-nowrap', {
                                      'table-active': currentItemId === item.id,
                                    })}
                                  >
                                    <td
                                      className="cursor-pointer"
                                      onClick={onClickDetail.bind(this, item)}
                                    >
                                      {item.id}
                                    </td>
                                    <td
                                      className="cursor-pointer"
                                      onClick={onClickDetail.bind(this, item)}
                                    >
                                      {item.name}
                                    </td>
                                    <td>
                                      <button
                                        onClick={onClickUpdate.bind(this, item)}
                                        className="btn btn-sm btn-light me-2"
                                        type="button"
                                      >
                                        <i className="bi bi-pencil me-2"></i>
                                        修改
                                      </button>
                                    </td>
                                  </tr>
                                );
                              })}
                            </tbody>
                          </table>

                          {data.content.length === 0 && (
                            <Alert message="暂无标签组" />
                          )}

                          <div className="my-4">
                            <nav aria-label="标签组分页">
                              <ul className="pagination justify-content-end">
                                <li
                                  className={classNames(
                                    'page-item',
                                    data.pageable.previous ? false : 'disabled',
                                  )}
                                >
                                  <a
                                    onClick={onClickPrevious}
                                    className="page-link cursor-pointer"
                                  >
                                    上一页
                                  </a>
                                </li>
                                <li
                                  className={classNames(
                                    'page-item',
                                    data.pageable.next ? false : 'disabled',
                                  )}
                                >
                                  <a
                                    onClick={onClickNext}
                                    className="page-link cursor-pointer"
                                  >
                                    下一页
                                  </a>
                                </li>
                              </ul>
                            </nav>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {detailItem && <DetailsTagGroupAdminPage />}

              {updateItem && <UpdateTagGroupAdminPage />}
            </div>
          </div>
        </div>
      </TagGroupAdminContext.Provider>
    );
  }

  if (queryAllTagQuery.error) {
    return <Alert message={queryAllTagQuery.error} type="error" />;
  }

  return <AlertLoad />;
}
